"use client";
import { listQuestionVoByPageUsingPost } from "@/api/questionController";
import TagList from "@/components/TagList";
import type {
  ActionType,
  ProColumns,
  ProFormInstance,
} from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { Button, message, Space, Tag } from "antd";
import { useRef, useState } from "react";
import DetailModal from "./components/DetailModal";
import Link from "next/link";

interface Props {
  // 默认值，展示服务端数据
  initData: API.QuestionVO[];
  total: number;
  searchParams?: Record<string, string>;
}
/**
 * 题目表格组件
 * @returns 题目表格组件
 */
const QuestionTable: React.FC<Props> = (props: Props) => {
  const { initData, total, searchParams } = props;

  const actionRef = useRef<ActionType>(undefined);
  const formRef = useRef<ProFormInstance>(undefined);

  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const [messageApi, contextHolder] = message.useMessage();
  // 题目列表
  const [questionList, setDefaultQuestionList] = useState<API.Question[]>(
    initData || []
  );
  // 题目总数
  const [defaultTotal, setDefaultTotal] = useState<number>(total || 0);

  // 判断是否 首次加载
  const [isFirstLoad, setIsFirstLoad] = useState<boolean>(true);

  const columns: ProColumns<API.QuestionVO>[] = [
    {
      title: "题目名",
      dataIndex: "title",
      valueType: "text",
      search: true,
      ellipsis: true,
      render: (_, entity) => {
        return <Link href={`/question/${entity.id}`}>{entity.title}</Link>;
      },
    },

    {
      title: "标签",
      dataIndex: "tags",
      valueType: "select",
      fieldProps: {
        mode: "tags",
      },
      render: (_, entity) => {
        return entity.tagList?.map((item) => (
          <Tag color="blue" key={item}>
            {item}
          </Tag>
        ));
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      valueType: "dateTime",
      search: false,
      sorter: true,
      hideInForm: true,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      valueType: "dateTime",
      search: false,
      sorter: true,
      hideInForm: true,
    },
    {
      title: "操作",
      dataIndex: "",
      search: false,
      hideInForm: true,
      render: (_, entity) => (
        <Space size="small">
          <Button
            type="link"
            onClick={() => {
              setCurrentRow(entity);
              setIsDetailModalOpen(true);
            }}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];
  const onCancel = () => {
    setIsDetailModalOpen(false);
  };
  return (
    <div className="question-table">
      {contextHolder}
      <ProTable<API.QuestionVO>
        columns={columns}
        actionRef={actionRef}
        formRef={formRef}
        cardBordered
        dataSource={questionList}
        request={async (params, sort, filter) => {
          if (isFirstLoad) {
            setIsFirstLoad(false);
            if (initData && total) {
              formRef?.current?.setFieldsValue({ ...searchParams });
              return;
            }
          }
          const sortField = Object.keys(sort)?.[0] || "createTime";
          const sortOrder = sort?.[sortField] || "descend";

          const { code, data } = await listQuestionVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          });
          const newData = data?.records || [];
          const newTotal = data?.total || 0;
          // 更新状态
          setDefaultQuestionList(newData);
          setDefaultTotal(newTotal);

          return {
            success: code === 0,
            data: newData,
            total: newTotal,
          };
        }}
        editable={{
          type: "multiple",
        }}
        columnsState={{
          persistenceKey: "pro-table-singe-demos",
          persistenceType: "localStorage",
          // defaultValue: {
          //   option: { fixed: "right", disable: true },
          // },
        }}
        rowKey="id"
        search={{
          labelWidth: "auto",
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          total: total,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        dateFormatter="string"
        headerTitle="题目列表"
      />
      <DetailModal
        isModalOpen={isDetailModalOpen}
        columns={columns}
        onCancel={onCancel}
      />
    </div>
  );
};
export default QuestionTable;
